import React, { useEffect, useState } from 'react';
import { useSetState } from 'ahooks';
import { Drawer, Select, Spin, message, Tooltip, Button, Modal } from 'antd';
import styles from './index.less';
import { titleMap, defaultPointerNum } from '../../dictionary';
// @ts-ignore
import { AIAndSimulate } from '../Charts/index';
import AdjustPolicyEditing from '../../Strategy/components/AdjustPolicyEditing';
import type {
  IComponentsIsErrorType,
  IComponentsIsLoadingType,
  IDataListType,
  IDataSourceListType,
  IForecastAndSimulateDataType,
  IFormValue,
  IPostFindAIRateDataParamsType,
  IPostFindStrategyPriceForecastParamsType,
  IPostQueryForecastAndSimulateParamsNewType,
  IPostQueryForecastAndSimulateParamsType,
  IPostQueryPriceDiffCurveParamsType,
  IPriceDiffCurveDataType,
  IReferenceStrategyDataType,
} from '../../type';
import {
  IBaseValueType,
  ICorrectionType,
  IForecastAndSimulateChartsLineType,
  IResetType,
  IShorttermForecastingRedesignPermissions,
  ISmoothStatusType,
  IStoreType,
  ITitleType,
  IUseType,
} from '../../type';
import ExplainTitle from '../ExplainTitle';
import OperationLog from '../../Strategy/components/OperationLog';
import {
  postAdjustProportionData,
  postFindAIRateData,
  postQueryForecastAndSimulate,
  postQueryLastQuoteStation,
  postQueryRateData,
  enableAI,
  getAiTacticsByStationIdAndMarkDate,
  queryForecastAndAiTactics,
  queryForecastAndManualStrategy,
  manualStrategySaveDataStatus,
} from '../../service';
import { TRAlert } from '#/components/index.js';
import { HttpCode } from '#/utils/contacts.js';
import { havePermissions, TIME_ENUM, ToFixed } from '../../tool';
import ReferenceStrategy from '../../Strategy/components/ReferenceStrategy';
import ChartsForecast from '../../Strategy/components/ChartsForecast';
import TRDefault from '@/tool/components/TRTheme/TRDefault';
// import { iconAiBlue } from '@/assets/icon/index.js';

const { confirm } = Modal;

interface IProps {
  /**
   * menuCode
   */
  menuCode?: string;
  /**
   * 请求数据
   */
  formValue?: IFormValue;
  /**
   * 查询
   */
  onSearch?: (
    params: IPostQueryForecastAndSimulateParamsType,
    ueryfindStrategyPriceForecastParams?: any,
    isUserFetchData?: boolean,
  ) => void;
  /**
   * 查询请求参数
   */
  queryParams?: IPostQueryForecastAndSimulateParamsType;
  /**
   * 权限
   */
  buttonPermissions?: any;
  /**
   * 禁用保存按钮
   */
  saveButtonDisabled?: boolean;
  /**
   * 是否显示抽屉
   */
  visible?: boolean;
  /**
   * 关闭函数
   */
  onClose?: () => void;
  /**
   * AI策略默认信参数
   */
  aiStrategyData?: any;
  /**
   * AI或人工
   */
  aiOrUser?: string;
  /**
   * 数据
   */
  data?: IForecastAndSimulateDataType[];
}

const AIForecast = (props: IProps) => {
  const {
    menuCode,
    saveButtonDisabled,
    buttonPermissions,
    formValue,
    visible = false,
    onClose,
    onSearch,
    queryParams,
    aiStrategyData,
    aiOrUser,
    data,
  } = props;
  const pointerNums = TIME_ENUM(defaultPointerNum);
  const [loading, setLoading] = useState<boolean>(false);
  const [userLoading, setUserLoading] = useState<boolean>(false);
  const [logVisible, setLogVisible] = useState<boolean>(false);
  const [aiTactics, setAiTactics] = useState<any>([]);
  const [aiTacticsValue, setAiTacticsValue] = useState<any>();
  const [aiData, setAiData] = useState([]);
  const [userChartData, setUserChartData] = useState<IForecastAndSimulateDataType[]>([]);
  const [switchState, setSwitchState] = useState<boolean>(false); //开关状态
  const [resetState, setResetState] = useState<number>(0); //重置状态
  const [manualStrategyFirstData, setManualStrategyFirstData] = useState<any>({}); //人工策略数据

  const [priceDiffCurveparams, setPriceDiffCurveparams] =
    useState<IPostQueryPriceDiffCurveParamsType>();
  const [forecastAndSimulateParams, setForecastAndSimulateParams] =
    useState<IPostQueryForecastAndSimulateParamsType>();
  const [priceDiffCurveData, setPriceDiffCurveData] = useState<IPriceDiffCurveDataType>({});
  const [forecastAndSimulateData, setForecastAndSimulateData] = useState<
    IForecastAndSimulateDataType[]
  >([]);

  const [adjustPolicyEditingData, setAdjustPolicyEditingData] = useState<IDataListType[]>([]);
  const [dataSourceList, setDataSourceList] = useState<IDataSourceListType[]>([]);
  const [defaultDataSourceId, setDefaultDataSourceId] = useState<number>();
  const [smoothStatus, setSmoothStatus] = useState<ISmoothStatusType>(ISmoothStatusType.BEZIER);
  const [quoteStationId, setQuoteStationId] = useState<number | null>(null);
  const [defaultCapacity, setDefaultCapacity] = useState<number | string>();
  const [componentsIsLoading, setComponentsIsLoading] = useSetState<IComponentsIsLoadingType>({
    priceDiffCurveIsLoading: false,
    forecastAndSimulateIsLoading: false,
    adjustPolicyEditingIsLoading: false,
    adjustPolicyEditingIsButtonLoading: false,
    strategicBenefitEstimationIsLoading: false,
    strategicBenefitEstimationAiIsLoading: false,
    aiForecastIsLoading: false,
    resetButIsLoading: false,
  });
  const [componentsIsError, setComponentsIsError] = useSetState<IComponentsIsErrorType>({
    priceDiffCurveIsError: false,
    forecastAndSimulateIsError: false,
    forecastAndSimulateFail: false,
    adjustPolicyEditingIsError: false,
    strategicBenefitEstimationIsError: false,
    strategicBenefitEstimationAIIsError: false,
  });

  // 策略效益预估
  const findStrategyPriceForecast = async (
    params: IPostFindStrategyPriceForecastParamsType,
    isReset = false,
  ) => {
    if (isReset) {
      setComponentsIsLoading({
        resetButIsLoading: true,
      });
    } else {
      setComponentsIsLoading({
        strategicBenefitEstimationIsLoading: true,
        strategicBenefitEstimationAiIsLoading: true,
      });
    }
    // findNowStrategyPriceForecast(params);
    // findAiStrategyPriceForecast(params);
    setComponentsIsLoading({
      resetButIsLoading: false,
    });
  };

  // 功率预测及模拟调整
  const queryForecastAndSimulate = async (params: IPostQueryForecastAndSimulateParamsType) => {
    setComponentsIsLoading({
      forecastAndSimulateIsLoading: true,
    });

    const _params: IPostQueryForecastAndSimulateParamsNewType = {
      ...params,
      dataFrom: switchState ? 8 : 9, //8, "-启用AI" \ 9, "-人工"
      smoothStatus: params.smoothStatus !== ISmoothStatusType.NONE ? params.smoothStatus : null,
    };

    userFetchData(_params);

    setComponentsIsLoading({
      strategicBenefitEstimationIsLoading: false,
      strategicBenefitEstimationAiIsLoading: false,
    });
    setForecastAndSimulateParams(params);
    setComponentsIsLoading({
      forecastAndSimulateIsLoading: false,
    });
  };

  // 调整策略编辑列表数据
  const queryRateData = async (params?: IFormValue, smoothStatusValue?: ISmoothStatusType) => {
    setComponentsIsLoading({
      adjustPolicyEditingIsLoading: true,
    });

    const _params = {
      markDate: formValue?.calendarDate,
      stationId: formValue?.stationId ? Number(formValue.stationId) : undefined,
    };

    // const res = switchState ? await enableAI(_params) : await postQueryRateData(params || {});

    if (switchState) {
      const res = await enableAI(_params || {});
      if (res && res.statusCode === HttpCode.SUCCESS) {
        setComponentsIsError({
          adjustPolicyEditingIsError: false,
        });
        const {
          dataList = [],
          // eslint-disable-next-line @typescript-eslint/no-shadow
          // smoothStatus = ISmoothStatusType.BEZIER,
          // eslint-disable-next-line @typescript-eslint/no-shadow
          // defaultCapacity = '0.000',
          // eslint-disable-next-line @typescript-eslint/no-shadow
          // eslint-disable-next-line @typescript-eslint/no-shadow
          // quoteStationId = null,
          // eslint-disable-next-line @typescript-eslint/no-shadow
          // defaultDataSourceId,
        } = res || {};
        const _adjustPolicyEditingData: IDataListType[] = (dataList || []).map(
          (item: IDataListType, index: number) => {
            return {
              ...item,
              beginTime: pointerNums[item?.beginIndex ?? 0] ?? '',
              endTime: pointerNums[item?.endIndex ?? 0] ?? '',
              maxValue: item?.maxValue ?? defaultCapacity,
              minValue: item?.minValue ?? '0.000',
              fixedValue: item?.fixedValue ?? '0.000',
              id: index + 1,
            };
          },
        );
        // setDefaultDataSourceId(defaultDataSourceId);
        // setDefaultCapacity(defaultCapacity ?? '0.000');
        // setSmoothStatus(smoothStatus || ISmoothStatusType.BEZIER);
        setAdjustPolicyEditingData(_adjustPolicyEditingData);
        // setQuoteStationId(quoteStationId);
        const _dataList: any[] = _adjustPolicyEditingData.map((item: IDataListType) => {
          const { id, beginTime, endTime, ...rest } = item;
          return {
            ...rest,
          };
        });
        const _queryForecastAndSimulateParams: IPostQueryForecastAndSimulateParamsType = {
          dataList: _dataList,
          markDate: params?.calendarDate,
          quoteStationId: quoteStationId ?? undefined,
          smoothStatus: smoothStatusValue ?? smoothStatus,
          stationId: params?.stationId ? Number(params?.stationId) : undefined,
          store: IStoreType.NO_CONSIDER,
        };
        queryForecastAndSimulate(_queryForecastAndSimulateParams);
      } else {
        setComponentsIsError({
          adjustPolicyEditingIsError: true,
        });
        message.error(res?.message || '系统异常');
      }
    } else {
      const _params = {
        ...params,
        reset: resetState,
      };
      // @ts-ignore
      const res = await postQueryRateData(_params || {});
      if (res && res.statusCode === HttpCode.SUCCESS) {
        setComponentsIsError({
          adjustPolicyEditingIsError: false,
        });
        const {
          dataList = [],
          // eslint-disable-next-line @typescript-eslint/no-shadow
          // smoothStatus = ISmoothStatusType.BEZIER,
          // eslint-disable-next-line @typescript-eslint/no-shadow
          defaultCapacity = '0.000',
          // eslint-disable-next-line @typescript-eslint/no-shadow
          dataSourceList = [],
          // eslint-disable-next-line @typescript-eslint/no-shadow
          quoteStationId = null,
          // eslint-disable-next-line @typescript-eslint/no-shadow
          defaultDataSourceId,
        } = res?.data || {};
        const _adjustPolicyEditingData: IDataListType[] = (dataList || []).map(
          (item: IDataListType, index: number) => {
            return {
              ...item,
              beginTime: pointerNums[item?.beginIndex ?? 0] ?? '',
              endTime: pointerNums[item?.endIndex ?? 0] ?? '',
              maxValue: item?.maxValue ?? defaultCapacity,
              minValue: item?.minValue ?? '0.000',
              fixedValue: item?.fixedValue ?? '0.000',
              id: index + 1,
            };
          },
        );
        setDefaultDataSourceId(defaultDataSourceId);
        setDefaultCapacity(defaultCapacity ?? '0.000');
        setDataSourceList(dataSourceList || []);
        // setSmoothStatus(smoothStatus || ISmoothStatusType.BEZIER);
        setAdjustPolicyEditingData(_adjustPolicyEditingData);
        setQuoteStationId(quoteStationId);
        const _dataList: any[] = _adjustPolicyEditingData.map((item: IDataListType) => {
          const { id, beginTime, endTime, ...rest } = item;
          return {
            ...rest,
          };
        });
        const _queryForecastAndSimulateParams: IPostQueryForecastAndSimulateParamsType = {
          dataList: _dataList,
          markDate: params?.calendarDate,
          quoteStationId: quoteStationId,
          smoothStatus: smoothStatusValue ?? smoothStatus,
          stationId: params?.stationId ? Number(params?.stationId) : undefined,
          store: IStoreType.NO_CONSIDER,
        };
        setManualStrategyFirstData(_queryForecastAndSimulateParams);
        queryForecastAndSimulate(_queryForecastAndSimulateParams);
      } else {
        setComponentsIsError({
          adjustPolicyEditingIsError: true,
        });
        message.error(res?.message || '系统异常');
      }
    }

    setLoading(false);
    setComponentsIsLoading({
      adjustPolicyEditingIsLoading: false,
    });
  };

  // 引用策略
  /*  const onReferenceStrategy = async () => {
    const res = await postQueryLastQuoteStation();
    await ReferenceStrategy.show({
      menuCode: menuCode,
      stationId: formValue?.stationId,
      quoteStationId: res?.data,
      formValue: formValue,
      onSubmit: (data: IReferenceStrategyDataType) => {
        // eslint-disable-next-line @typescript-eslint/no-shadow
        const { quoteDataList = [], quoteStationId } = data;
        const _adjustPolicyEditingData: IDataListType[] = [];
        quoteDataList.map((item: IDataListType, index: number) => {
          _adjustPolicyEditingData.push({
            ...item,
            dataSourceId: dataSourceList.find((i) => i.dataSourceId === item?.dataSourceId)
              ? item?.dataSourceId
              : defaultDataSourceId,
            beginTime: pointerNums[item?.beginIndex ?? 0] ?? '',
            endTime: pointerNums[item?.endIndex ?? 0] ?? '',
            maxValue: defaultCapacity,
            minValue: '0.000',
            fixedValue:
              Number(item?.fixedValue) > Number(defaultCapacity)
                ? defaultCapacity ?? '0.000'
                : item?.fixedValue ?? '0.000',
            id: index + 1,
          });
        });
        const _dataList: any[] = _adjustPolicyEditingData.map((item: IDataListType) => {
          const { id, beginTime, endTime, ...rest } = item;
          return {
            ...rest,
          };
        });
        const _queryForecastAndSimulateParams: IPostQueryForecastAndSimulateParamsType = {
          dataList: _dataList,
          markDate: formValue?.calendarDate,
          quoteStationId: quoteStationId,
          smoothStatus: smoothStatus,
          stationId: formValue?.stationId ? Number(formValue?.stationId) : undefined,
          store: IStoreType.NO_CONSIDER,
        };
        queryForecastAndSimulate(_queryForecastAndSimulateParams);
        setQuoteStationId(quoteStationId as unknown as number);
        // saveLastQuoteStation(quoteStationId);
        setAdjustPolicyEditingData(_adjustPolicyEditingData);
      },
    });
  }; */

  // 图形策略
  /* const onReferenceChart = async () => {
    const _curveDataList =
      forecastAndSimulateData.find((item) => {
        return item.dataSource === IForecastAndSimulateChartsLineType.LINE_SIX;
      })?.values || [];
    if (_curveDataList.length > 0) {
      const _adjustPolicyEditingData: IDataListType[] = _curveDataList.map(
        (item: number, index: number) => {
          return {
            useType: IUseType.FIXATION,
            rateValue: 100,
            dataSourceId: defaultDataSourceId,
            beginTime: pointerNums[index ?? 0] ?? '',
            beginIndex: index,
            endIndex: index,
            endTime: pointerNums[index ?? 0] ?? '',
            maxValue: ToFixed(defaultCapacity, 3),
            minValue: '0.000',
            fixedValue:
              Number(item) > Number(defaultCapacity)
                ? ToFixed(defaultCapacity, 3) ?? '0.000'
                : ToFixed(item, 3) ?? '0.000',
            id: index + 1,
          };
        },
      );
      await ChartsForecast.show({
        data: _adjustPolicyEditingData,
        onSubmit: (val: IDataListType[]) => {
          const _dataList: any[] = val.map((item: IDataListType) => {
            const { id, beginTime, endTime, ...rest } = item;
            return {
              ...rest,
            };
          });
          const _queryForecastAndSimulateParams: IPostQueryForecastAndSimulateParamsType = {
            dataList: _dataList,
            markDate: formValue?.calendarDate,
            smoothStatus: smoothStatus,
            stationId: formValue?.stationId ? Number(formValue?.stationId) : undefined,
            store: IStoreType.NO_CONSIDER,
          };
          queryForecastAndSimulate(_queryForecastAndSimulateParams);
          setAdjustPolicyEditingData(val);
        },
      });
    } else {
      message.error('功率预测数据缺失!');
    }
  }; */

  // 改变平滑方式
  /* const onChangeSmoothWay = (e: ISmoothStatusType) => {
    setSmoothStatus(e);
    const _forecastAndSimulateParams = {
      ...forecastAndSimulateParams,
      smoothStatus: e,
    };
    queryForecastAndSimulate(_forecastAndSimulateParams);
  }; */

  // 重置调整策略编辑
  /* const onReset = (reset = IResetType.NO_RESET) => {
    setComponentsIsLoading({
      adjustPolicyEditingIsButtonLoading: true,
    });
    setSwitchState(false);
    setSmoothStatus(ISmoothStatusType.BEZIER);
    setResetState(reset);
    // @ts-ignore
    queryRateData({ ...formValue }, ISmoothStatusType.BEZIER);
    setComponentsIsLoading({
      adjustPolicyEditingIsButtonLoading: false,
    });
  }; */

  //AI策略算法选择
  const handleAITacticsValueChange = (value: string) => {
    setAiTacticsValue(value);
  };

  //保存AI策略编辑
  const onAiSave = async () => {
    if (aiTacticsValue === undefined || aiTacticsValue === '' || aiTacticsValue === null) {
      message.error('请选择算法');
      return;
    } else {
      const tactic = aiTactics.find((tactic: any) => tactic.value === aiTacticsValue);
      const tacticId = tactic ? tactic.id : null;

      const resoult = havePermissions(
        IShorttermForecastingRedesignPermissions.SAVEBUTTON,
        buttonPermissions,
      );
      if (resoult) {
        setComponentsIsLoading({
          adjustPolicyEditingIsButtonLoading: true,
        });
        const _adjustPolicyEditingData: IDataListType[] = (aiData?.dataList || []).map(
          (item: IDataListType, index: number) => {
            return {
              ...item,
              timeSlot: `${pointerNums[item?.beginIndex ?? 0] ?? ''}-${
                pointerNums[item?.endIndex ?? 0] ?? ''
              }`,
            };
          },
        );

        const _params: IPostQueryForecastAndSimulateParamsNewType = {
          dataFrom: tacticId,
          // @ts-ignore
          dataList: _adjustPolicyEditingData,
          markDate: formValue?.calendarDate,
          quoteStationId: quoteStationId ?? undefined,
          stationId: formValue?.stationId ? Number(formValue?.stationId) : undefined,
          store: IStoreType.NO_CONSIDER,
        };
        const res = await postAdjustProportionData(_params);
        if (res && res.statusCode === HttpCode.SUCCESS) {
          queryRateData(formValue || {});
          message.success('保存成功');
          onClose && onClose();
        } else {
          message.error(res.message || '保存失败');
        }
        setComponentsIsLoading({
          adjustPolicyEditingIsButtonLoading: false,
        });
        if (queryParams) onSearch && onSearch(queryParams, undefined, true); // 重新查询
      }
    }
    onClose && onClose();
  };

  /* // 保存调整策略编辑
  const onSave = async () => {
    const resoult = havePermissions(
      IShorttermForecastingRedesignPermissions.SAVEBUTTON,
      buttonPermissions,
    );
    if (resoult) {
      setComponentsIsLoading({
        adjustPolicyEditingIsButtonLoading: true,
      });
      let _adjustPolicyEditingData: IDataListType[] = adjustPolicyEditingData.map((item) => {
        const { beginTime, endTime, ...rest } = item;
        return {
          ...rest,
          beginIndex: pointerNums.findIndex((i) => i === beginTime),
          endIndex: pointerNums.findIndex((i) => i === endTime),
          timeSlot: `${beginTime}-${endTime}`,
        };
      });
      _adjustPolicyEditingData = _adjustPolicyEditingData.filter((item) => {
        return item.beginIndex !== -1 && item.endIndex !== -1;
      });

      const _params: IPostQueryForecastAndSimulateParamsNewType = {
        dataFrom: switchState ? 8 : 9, //8, "-启用AI" \ 9, "-人工"
        dataList: _adjustPolicyEditingData,
        markDate: formValue?.calendarDate,
        quoteStationId: quoteStationId ?? undefined,
        smoothStatus: smoothStatus,
        stationId: formValue?.stationId ? Number(formValue?.stationId) : undefined,
        store: IStoreType.NO_CONSIDER,
      };
      const res = await postAdjustProportionData(_params);
      if (res && res.statusCode === HttpCode.SUCCESS) {
        setResetState(IResetType.NO_RESET);
        queryRateData(formValue || {});
        message.success('保存成功');
        onClose && onClose();
      } else {
        message.error(res.message || '保存失败');
      }
      setComponentsIsLoading({
        adjustPolicyEditingIsButtonLoading: false,
      });
      if (queryParams) onSearch && onSearch(queryParams); // 重新查询
    }
  }; */

  // 调整策略编辑
  /* const onChangeAdjustPolicyEditingData = (data: IDataListType[], isRefresh: boolean = true) => {
    let _adjustPolicyEditingData: IDataListType[] = data.map((item) => {
      const { beginTime, endTime, ...rest } = item;
      return {
        ...rest,
        beginIndex: pointerNums.findIndex((i) => i === beginTime),
        endIndex: pointerNums.findIndex((i) => i === endTime),
        timeSlot: `${beginTime}-${endTime}`,
      };
    });
    _adjustPolicyEditingData = _adjustPolicyEditingData.filter((item) => {
      return item.beginIndex !== -1 && item.endIndex !== -1;
    });
    const _params: IPostQueryForecastAndSimulateParamsType = {
      dataList: _adjustPolicyEditingData,
      markDate: formValue?.calendarDate,
      quoteStationId: quoteStationId ?? undefined,
      smoothStatus: smoothStatus,
      stationId: formValue?.stationId ? Number(formValue?.stationId) : undefined,
      store: IStoreType.NO_CONSIDER,
    };
    setAdjustPolicyEditingData(data);
    if (isRefresh) {
      queryForecastAndSimulate(_params);
    }
  }; */

  // 关闭操作日志
  const onLogClose = () => {
    setLogVisible(false);
  };

  // 取消
  const _onCancel = () => {
    if (aiTacticsValue === undefined || aiTacticsValue === '' || aiTacticsValue === null) {
      onClose && onClose();
      return;
    }
    confirm({
      title: '数据未保存，是否确认关闭？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        if (aiOrUser === 'ai') {
          setAiTacticsValue(null);
          setAiTactics([]);
          setAiData([]);
        }
        setSmoothStatus(ISmoothStatusType.BEZIER);
        onClose && onClose();
      },
    });
    // onClose && onClose();
  };

  // AI策略开关
  /* const onChangeSwitchState = (checked: boolean) => {
    setSwitchState(checked);
  }; */

  // AI策略初始化
  const fetchAIData = async (formValue1: IFormValue, aiTacticsValue: string) => {
    setLoading(true);
    const _params: IPostQueryForecastAndSimulateParamsType = {
      markDate: formValue1.calendarDate,
      stationId: formValue1?.stationId ? Number(formValue1.stationId) : undefined,
    };
    try {
      const res = await getAiTacticsByStationIdAndMarkDate(_params);
      if (res?.statusCode === HttpCode.SUCCESS) {
        setAiTactics(res.data);
      } else {
        message.error(res?.message || '获取AI策略算法列表失败');
      }

      const aiParams = {
        algorithm: aiTacticsValue,
        ..._params,
      };
      const aiRes = await queryForecastAndAiTactics(aiParams);
      if (aiRes?.statusCode === HttpCode.SUCCESS) {
        setAiData(aiRes);
      } else {
        message.error(aiRes?.message || '获取AI策略图数据失败');
      }
    } catch (error) {
      message.error('请求失败');
    } finally {
      setLoading(false);
    }
  };

  const userFetchData = async (_params: IPostQueryForecastAndSimulateParamsType) => {
    setUserLoading(true);
    try {
      const res = await queryForecastAndManualStrategy(_params);
      if (res?.statusCode === HttpCode.SUCCESS) {
        setUserChartData(res.data);
      } else {
        message.error(res?.message || '获取人工策略图表数据失败');
      }
    } catch (error) {
      message.error('数据请求失败');
    } finally {
      setUserLoading(false);
    }
  };

  /* const defaultSmoothStatus = (values: ISmoothStatusType) => {
    if (values) {
      setSmoothStatus(values);
    }
  }; */

  /* const getBtnStuatus = async () => {
    const _params: IPostQueryForecastAndSimulateParamsType = {
      markDate: formValue?.calendarDate,
      stationId: formValue?.stationId ? Number(formValue.stationId) : undefined,
    };
    const res = await manualStrategySaveDataStatus(_params);
    return res;
  };
 */
  /*  useEffect(() => {
    getBtnStuatus().then((status) => {
      onChangeSwitchState(status.switchState);
      defaultSmoothStatus(status.smoothStatus);
    });
  }, []); */

  useEffect(() => {
    if (visible && formValue) {
      if (aiOrUser === 'ai') {
        fetchAIData(formValue, aiTacticsValue);
      }
      /*  setComponentsIsLoading({ adjustPolicyEditingIsButtonLoading: true });
      queryRateData({ ...formValue }).finally(() => {
        setComponentsIsLoading({ adjustPolicyEditingIsButtonLoading: false });
      }); */
    }
  }, [visible, aiTacticsValue, formValue, aiOrUser, switchState, resetState]);

  return (
    <Drawer
      width={1400}
      className={styles.operateLogModal}
      visible={visible}
      onClose={_onCancel}
      title={
        <div className={styles.titleDiv}>
          {/* <img src={iconAiBlue} className={styles.titleLogo} /> */}
          <span className={styles.title}>
            交易操作台 / 省内现货申报 /{' '}
            <span style={{ color: 'var(--font)' }}>
              {aiOrUser === 'user' ? '人工策略' : 'AI策略'}
            </span>
          </span>
        </div>
      }
      footer={null}
    >
      <div className={styles.container}>
        <div className={styles.center}>
          <div className={styles.aiForecast}>
            {aiOrUser === 'user' /* <div className={styles.right}>
                <div className={styles.rightBottom}>
                  <div className={styles.header}>
                    <div className={styles.title}>
                      <ExplainTitle title={titleMap[ITitleType.ADJUST_POLICY_EDITING].title} />
                      <div
                        className={styles.operationLog}
                        onClick={() => {
                          setLogVisible(true);
                        }}
                      >
                        <span className={styles.title}>操作日志</span>
                      </div>
                    </div>
                    <div className={styles.btnBox}>
                      <Button
                        className={styles.resetBut}
                        onClick={() => onReset(IResetType.RESET)}
                        loading={componentsIsLoading.adjustPolicyEditingIsButtonLoading}
                      >
                        重置
                      </Button>
                      <Button
                        className={styles.save}
                        onClick={onSave}
                        disabled={
                          componentsIsError.adjustPolicyEditingIsError || saveButtonDisabled
                        }
                        type="primary"
                        loading={componentsIsLoading.adjustPolicyEditingIsButtonLoading}
                      >
                        保存
                      </Button>
                    </div>
                  </div>
                  <div className={styles.bottom}>
                    <AdjustPolicyEditing
                      smoothStatus={smoothStatus}
                      defaultSmoothStatus={defaultSmoothStatus}
                      defaultCapacity={defaultCapacity}
                      saveButtonDisabled={saveButtonDisabled}
                      data={adjustPolicyEditingData}
                      dataSourceList={dataSourceList}
                      error={componentsIsError.adjustPolicyEditingIsError}
                      userLoading={userLoading}
                      loading={componentsIsLoading.adjustPolicyEditingIsLoading}
                      buttonLoading={componentsIsLoading.adjustPolicyEditingIsButtonLoading}
                      aiForecastIsLoading={componentsIsLoading?.aiForecastIsLoading}
                      aiForecastIsDisabled={
                        componentsIsLoading.adjustPolicyEditingIsLoading ||
                        componentsIsLoading.forecastAndSimulateIsLoading
                      }
                      chartsForecastDisabled={componentsIsLoading.forecastAndSimulateIsLoading}
                      // onChangeSmoothWay={onChangeSmoothWay}
                      onReset={onReset}
                      onChange={onChangeAdjustPolicyEditingData}
                      onReferenceStrategy={onReferenceStrategy}
                      // onReferenceChart={onReferenceChart}
                      formValue={formValue}
                      aiStrategyData={aiStrategyData}
                      userChartData={userChartData}
                      visible={visible}
                      switchState={switchState}
                      onChangeSwitchState={onChangeSwitchState}
                    />
                  </div>
                </div>
              </div> */ ? null : (
              <div>
                <div className={styles.aiForecastTop}>
                  <span className={styles.forecastText}>
                    {aiOrUser === 'user' ? '人工策略' : 'AI策略'}
                    <div
                      className={styles.operationLog}
                      onClick={() => {
                        setLogVisible(true);
                      }}
                    >
                      <span className={styles.title}>操作日志</span>
                    </div>
                  </span>
                  <div>
                    <Select
                      style={{ width: 200 }}
                      value={aiTacticsValue}
                      onChange={handleAITacticsValueChange}
                      loading={loading}
                      options={aiTactics}
                      allowClear
                      placeholder="请选择算法"
                    />
                    <Button
                      type="primary"
                      style={{ marginLeft: 16, width: 100 }}
                      onClick={onAiSave}
                      loading={componentsIsLoading.adjustPolicyEditingIsButtonLoading}
                      disabled={componentsIsError.adjustPolicyEditingIsError || saveButtonDisabled}
                    >
                      保存
                    </Button>
                  </div>
                </div>
                <div className={styles.aiForecastBottom}>
                  <div className={styles.content}>
                    {loading ? (
                      <Spin />
                    ) : aiData?.data?.length > 0 ? (
                      <div className={styles.charts}>
                        <AIAndSimulate data={aiData.data} date={formValue?.calendarDate} />
                      </div>
                    ) : (
                      <TRDefault type={'emptysm'} message={'暂无数据'} />
                    )}
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
        <OperationLog
          visible={logVisible}
          onClose={onLogClose}
          queryValue={{
            markDate: formValue?.calendarDate,
            stationId: formValue?.stationId,
            type: aiOrUser === 'ai' ? 1 : 2,
          }}
        />
      </div>
    </Drawer>
  );
};

export default AIForecast;
